import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_navigation/src/extension_navigation.dart';

import 'base_page.dart';

/// 整个Bar分为左中右三部分
/// leftWidget：展示在左边的控件，默认为返回按钮，点击返回上一级页面
/// titleWidget：展示在中间的标题控件，假如不设置默认为Text，title为文本，titleStyle为文本样式
/// rightWidgets：展示在右边的控件列表
class BaseAppBar extends BaseStatelessWidget implements PreferredSizeWidget {
  /// 标题
  final String title;

  /// 标题样式
  final TextStyle? titleStyle;

  /// 是否展示左边按钮
  final bool showLeftButton;

  /// 左边控件
  final Widget? leftWidget;

  /// 标题视图
  final Widget? titleWidget;

  /// 右边控件列表
  final List<Widget>? rightWidgets;

  /// 背景颜色
  final Color? backgroundColor;

  final double? toolbarHeight;

  final bool automaticallyImplyLeading;

  /// By default, the value of [AppBar.leadingWidth] is 56.0.
  final double? leadingWidth;

  /// appbar样式
  final SystemUiOverlayStyle? systemOverlayStyle;

  BaseAppBar(
    this.title, {
    this.titleStyle,
    this.showLeftButton = true,
    this.rightWidgets,
    this.leftWidget,
    this.titleWidget,
    this.backgroundColor,
    this.systemOverlayStyle,
    this.toolbarHeight = 52,
    this.automaticallyImplyLeading = true,
    this.leadingWidth,
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: titleWidget ?? Text(title, style: titleStyle),
      centerTitle: true,
      backgroundColor: backgroundColor,
      elevation: 0,
      titleSpacing: titleWidget != null ? 0 : null,
      systemOverlayStyle: systemOverlayStyle ??
          const SystemUiOverlayStyle(
              statusBarColor: Colors.transparent,
              systemNavigationBarColor: Colors.white,
              systemNavigationBarIconBrightness: Brightness.light,
              statusBarIconBrightness: Brightness.dark),
      leading: showLeftButton ? (leftWidget ?? _buildBackWidget()) : null,
      leadingWidth: leadingWidth,
      actions: rightWidgets,
      toolbarHeight: toolbarHeight,
      automaticallyImplyLeading: automaticallyImplyLeading,
    );
  }

  /// 回退按钮
  Widget _buildBackWidget() {
    return IconButton(
      icon: const Icon(Icons.arrow_back),
      onPressed: () async {
        var canPop = navigator?.canPop();
        if (canPop != null && canPop) {
          Get.back();
        } else {
          SystemNavigator.pop();
        }
      },
    );
  }

  @override
  Size get preferredSize => Size.fromHeight(toolbarHeight ?? kToolbarHeight);
}
